package com.ynu.znkz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ynu.znkz.commomutils.IdWorker;
import com.ynu.znkz.commomutils.R;
import com.ynu.znkz.commomutils.ResultCode;
import com.ynu.znkz.commomutils.SecuritySHA1Util;
import com.ynu.znkz.entity.User;
import com.ynu.znkz.entity.vo.LoginVo;
import com.ynu.znkz.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //用户登录
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo) {
        //对用户名和密码进行登陆验证
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String secretpwd = "";
        try {
            secretpwd = SecuritySHA1Util.shaEncode(password);
        }catch (Exception e) {
            e.printStackTrace();
        }
        User user = userService.getByUserNameAndPassword(username, secretpwd);
        if (user != null) {
            //登陆成功，用雪花算法生成随机token
            String id = new IdWorker().nextId() + "";
            //将用户登录对象转为json格式的字符串
            loginVo.setId(user.getId());
            loginVo.setRealName(user.getRealName());
            String loginInfo = JSON.toJSONString(loginVo);
            //以该token为key将用户信息存入redis中，并设置缓存失效时间(6hours)
            redisTemplate.boundValueOps(id + "").set(loginInfo, 6, TimeUnit.HOURS);
            return R.ok().data("token", id);
        } else {
            return R.error().message("用户名或密码错误");
        }
    }

    //请求用户信息
    @GetMapping("/info")
    public R info (@RequestHeader("Admin-Token") String token){
        String userStr = null;
        LoginVo user;
        if (!StringUtils.isEmpty(token)) {
            userStr = redisTemplate.opsForValue().get(token);
        }
        user = JSONObject.parseObject(userStr, LoginVo.class);
        if (null != user) {
            return R.ok().data("roles", "[admin]")
                    .data("avatar", "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1994349953,4058704947&fm=26&gp=0.jpg")
                    .data("loginInfo", user);
        } else {
            return R.error().data("code", ResultCode.INVALID_TOKEN);
        }
    }

    //用户登出
    @GetMapping("/logout")
    public R logout(@RequestHeader("Admin-Token") String token) {
        //删除redis中的用户token信息
        Boolean isDeleted = redisTemplate.delete(token);
        if(isDeleted) return R.ok();
        else return R.error();
    }

    //用户注册
    @PostMapping("/register")
    public R register(@RequestBody User userInfo) {
        userInfo.setIsDeleted(false);
        //对用户密码进行加密（不加盐）
        String pwd = userInfo.getPassword();
        try {
            String secretPwd = SecuritySHA1Util.shaEncode(pwd);
            userInfo.setPassword(secretPwd);
        }catch (Exception e) {
            e.printStackTrace();
        }
        boolean flag = userService.save(userInfo);
        if(flag) return R.ok().data("code", ResultCode.SUCCESS);
        return R.error().data("code", ResultCode.ERROR);
    }

    //判断注册的用户名是否存在
    @GetMapping("/avaliable/{username}")
    public R isAvailableUsername(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        int count = userService.count(queryWrapper);
        if(count == 0) return R.ok().data("code", ResultCode.SUCCESS);
        return R.error().data("code", ResultCode.ERROR);
    }
}
